const tencentcloud = require('tencentcloud-sdk-nodejs');
const AsrClient = tencentcloud.asr.v20190614.Client;

// 创建ASR客户端
function createAsrClient() {
  const clientConfig = {
    credential: {
      secretId: process.env.TENCENT_SECRET_ID,
      secretKey: process.env.TENCENT_SECRET_KEY,
    },
    region: process.env.TENCENT_REGION || 'ap-guangzhou',
    profile: {
      httpProfile: {
        endpoint: 'asr.tencentcloudapi.com',
      },
    },
  };

  return new AsrClient(clientConfig);
}

// 实时语音识别
async function recognizeRealtime(audioData, sessionId) {
  try {
    console.log(`开始实时语音识别，会话ID: ${sessionId}`);
    
    const client = createAsrClient();
    
    // 构建请求参数
    const params = {
      "EngineType": "16k_zh",
      "VoiceFormat": "wav",
      "SpeakerDiarization": 0,
      "FilterDirty": 0,
      "FilterModal": 0,
      "FilterPunc": 0,
      "ConvertNumMode": 1,
      "FirstChannelOnly": 1,
      "WordInfo": 2,
      "Data": audioData,
      "SessionId": sessionId || Date.now().toString()
    };
    
    // 调用腾讯云ASR API
    const result = await client.SentenceRecognition(params);
    console.log(`语音识别成功，结果: ${JSON.stringify(result)}`);
    
    return result;
  } catch (error) {
    console.error('实时语音识别失败:', error);
    throw error;
  }
}

// 查询语音识别任务状态
async function getTaskStatus(taskId) {
  try {
    console.log(`查询语音识别任务状态，任务ID: ${taskId}`);
    
    const client = createAsrClient();
    
    // 构建请求参数
    const params = {
      "TaskId": taskId
    };
    
    // 调用腾讯云ASR API
    const result = await client.DescribeTaskStatus(params);
    console.log(`查询任务状态成功，结果: ${JSON.stringify(result)}`);
    
    return result;
  } catch (error) {
    console.error('查询任务状态失败:', error);
    throw error;
  }
}

module.exports = {
  recognizeRealtime,
  getTaskStatus
};